package com.frank.demo.mq.rabbitmq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created by zhy on 2018/4/20.
 */
public class Rabbitmq {
    private final static String QUEUE_NAME = "message_test";


    public static void main(String[] args) throws IOException, InterruptedException, TimeoutException {
        //打开连接和创建频道，与发送端一样
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        factory.setVirtualHost("/message");
        factory.setUsername("guest");
        factory.setPassword("guest");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();


        //声明队列，主要为了防止消息接收者先运行此程序，队列还不存在时创建队列。
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

//        channel.confirmSelect();
//        channel.addConfirmListener( new ConfirmListener() {
//            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
//                System.out.println("Ack, SeqNo: " + deliveryTag + ", multiple: " + multiple);
//            }
//            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
//                System.out.println("Nack, SeqNo: " + deliveryTag + ", multiple: " + multiple);
//            }
//        });

        //发送消息到队列中
//        channel.txSelect();//开启事务
        String message = "Hello RabbitMQ";
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
//        channel.txRollback();

    }
}
